package dwarffortress.tools;

import java.util.zip.Deflater;
import java.util.zip.Inflater;
import java.util.zip.DataFormatException;
import java.io.*;

public class PackFile {
    private static void writeSize(OutputStream s, int size) throws IOException {
        byte b[] = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (size & 0xff);
            size = size >> 8;
        }
        s.write(b);
    }

    public static void main(String[] args) throws IOException, DataFormatException {
        byte in_buf[] = new byte[20000];
        byte[] out_buf = new byte[in_buf.length * 2 + 10];

        for (String file : args) {
            String to_file_name;
            if (file.toLowerCase().endsWith(".raw")) {
                to_file_name = file.substring(0, file.length() - 4);
            } else {
                to_file_name = file + ".packed";
            }

            FileInputStream in = new FileInputStream(file);

            FileOutputStream out = new FileOutputStream(to_file_name);
            while (true) {
                int read = in.read(in_buf);
                if (read < 0) {
                    break;
                }
                Deflater zlib = new Deflater();
                zlib.setInput(in_buf, 0, read);
                zlib.finish();
                int written = zlib.deflate(out_buf);
                writeSize(out, written);
                out.write(out_buf, 0, written);
                written = zlib.deflate(out_buf);
                if (0 != written) {
                    System.err.println("Problem writing");
                }
            }
            out.close();
        }
    }
}